package algorithms;

/**
 * @功能
 * @创建时间 2020/5/17
 */
public class Code01_RotateString {
    /**
     * 左部分交换，右部分交换，然后整体交换
     *
     * @param s
     * @param leftSize
     * @return
     */
    public static String rotate1(String s, int leftSize) {
        if (leftSize < 0 || leftSize > s.length()) {
            return s;
        } else {
            return process1(s.toCharArray(), 0, leftSize - 1, s.length() - 1);
        }
    }

    public static String process1(char[] str, int L, int M, int R) {
        reverse(str, L, M);
        reverse(str, M + 1, R);
        reverse(str, L, R);
        return String.valueOf(str);


    }

    public static void reverse(char[] str, int L, int R) {
        while (L < R) {
            char tmp = str[L];
            str[L++] = str[R];
            str[R--] = tmp;
        }
    }

    public static String rotate2(String s, int leftSize) {
        if (leftSize < 0 || leftSize > s.length()) {
            return s;
        }
        char[] str = s.toCharArray();
        int L = 0;
        int R = str.length - 1;
        int lpart = leftSize;
        int rpart = str.length - leftSize;
        int same = Math.min(lpart, rpart);
        int diff = lpart - rpart;
        exchange(str, L, R, same);
        while (diff!=0){
            if(diff>0){
                L += same;
                lpart = diff;
            }else {
                R -= same;
                rpart = -diff;
            }
            same = Math.min(lpart,rpart);
            diff = lpart - rpart;
            exchange(str,L,R,same);
        }
        return String.valueOf(str);
    }

        public static void exchange(char[] chas, int start, int end, int size) {
        int i = end -size + 1;
        char tmp = 0;
        while (size-- != 0){
            tmp = chas[start];
            chas[start] = chas[i];
            chas[i] = tmp;
            start++;
            i++;
        }
    }
}